import {useModel} from '@@/exports';
import {DownloadOutlined, PlusOutlined, UploadOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {EditableProTable} from '@ant-design/pro-components';
import {Button, Form, message, notification, Popconfirm, Space, Tooltip, Upload, UploadProps} from 'antd';
import React, {useEffect, useState} from 'react';
import {
  addMonthlyPlanningKeyProcessUsingPOST,
  deleteMonthlyPlanningKeyProcessUsingDELETE,
  editMonthlyPlanningKeyProcessUsingPUT,
  listMonthlyPlanningKeyProcessDTOUsingGET
} from "@/services/model/monthlyPlanningController";
import {listBaseStepUsingGET} from "@/services/model/baseStepController";
import {errorConfig} from "@/requestErrorConfig";
import CustomSelect from "@/pages/components/CustomSelect";

type RightTableProps = {
  clickMonthlyPlanningNumber: undefined | API.MonthlyPlanningNumberDTO;
  leftActionRef:  React.MutableRefObject<ActionType | undefined>;
  rightActionRef:  React.MutableRefObject<ActionType | undefined>;
};

const RightTable: React.FC<RightTableProps> = (props: RightTableProps) => {
  const {initialState} = useModel('@@initialState');
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly API.MonthlyPlanningKeyProcessDTO[]>([]);
  const [baseStepList, setBaseStepList] = useState<readonly API.BaseStepDTO[]>(
    [],
  );
  const [selectValue, setSelectValue] = useState('');
  const [form] = Form.useForm();
  // 弹出上传信息数据
  type NotificationType = 'success' | 'info' | 'warning' | 'error';
  const [api, contextHolder] = notification.useNotification();
  const openNotification = (type: NotificationType, info: string) => {
    api[type]({
      message: "上传信息",
      description: info,
      duration: 0,
      placement: "bottomRight"
    });
  };

  useEffect(() => {
    listBaseStepUsingGET().then((result) => {
      if (result.code === 0 && result.data) {
        setBaseStepList(result.data);
      }
    });
  }, []);

  const initKeyProcessList = async () => {

    if (props.clickMonthlyPlanningNumber?.productionLineCode === undefined) {
      return {
        data: [],
      };
    }
    const result = await listMonthlyPlanningKeyProcessDTOUsingGET({
      commitUserId: initialState?.currentUser?.id,
      productionLineCode: props?.clickMonthlyPlanningNumber?.productionLineCode,
      month: props?.clickMonthlyPlanningNumber?.month,
      year: props?.clickMonthlyPlanningNumber?.year,
    })
    return {
      data: result.data
    };
  };
  const KeyProcessList = () => {
    return (
    <CustomSelect name={"工序名称"}
                  selectDate={selectValue}
                  setSelectData={setSelectValue}
                  datalist={baseStepList.map(item => {
                    return {id: item.code, name: item.name + " [" + item.code + "]"}
                  })}/>
    );
  };

  const onDelete = async (id: number) => {
    const result = await deleteMonthlyPlanningKeyProcessUsingDELETE({
      id,
      currentUserId: initialState?.currentUser?.id,
    });
    if (result.code === 0 && result.data) {
      message.success('删除成功');
      props.rightActionRef.current?.reload();
    } else {
      message.error(result.message);
    }
  };
  const onSave = async (row: API.MonthlyPlanningKeyProcessDTO) => {
    const currentUserId = initialState?.currentUser?.id;
    const newProductionPlanningKeyProcess: API.AddMonthlyPlanningKeyProcessQuery = {
      currentUserId,
      productionLineCode: props?.clickMonthlyPlanningNumber?.productionLineCode,
      keyStepCode: selectValue,
      planningCapacity: row.planningCapacity,
      sort: row.sort,
      month: props?.clickMonthlyPlanningNumber?.month,
      planningNumber: props?.clickMonthlyPlanningNumber?.planningNumber,
      year: props?.clickMonthlyPlanningNumber?.year,

    };
    const result = await addMonthlyPlanningKeyProcessUsingPOST(newProductionPlanningKeyProcess);
    if (result.code === 0 && result.data) {
      message.success('添加成功');
      props.rightActionRef.current?.reload();
    } else {
      message.warning(result.message);
    }
    props.rightActionRef.current?.reload();
  };

  const onEdit = async (record: API.MonthlyPlanningKeyProcessDTO) => {
    const currentUserId = initialState?.currentUser?.id;
    const newMonthlyPlanningKeyProcess: API.EditMonthlyPlanningKeyProcessQuery = {
      currentUserId,
      id: record.id,
      planningCapacity: record.planningCapacity,
      sort: record.sort,
    };
    const result = await editMonthlyPlanningKeyProcessUsingPUT(newMonthlyPlanningKeyProcess);
    if (result.code === 0 && result.data) {
      message.success('修改成功');
    } else {
      message.warning(result.message);
    }
    props.rightActionRef.current?.reload();
  };

  const columns: ProColumns<API.MonthlyPlanningKeyProcessDTO>[] = [
    {
      title: 'id',
      key: 'id',
      dataIndex: 'id',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '关键工序名称',
      key: 'keyStepName',
      dataIndex: 'keyStepName',
      editable: (text, record: any) => {
        return record.type === "addProductionLineKeyProcess";
      },
      renderFormItem: () => <KeyProcessList/>,
    },
    {
      title: '月产能规划',
      key: 'planningCapacity',
      dataIndex: 'planningCapacity',
      valueType: 'digit',
      width: 120
    },
    {
      title: '排序',
      key: 'sort',
      dataIndex: 'sort',
      valueType: 'digit',
      width: 100,
      tooltip: "产线看板关键工序从上到下的顺序"
    },

    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            form.resetFields();
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key={'onDelete'}
          title="你想要删除这个产线配置吗"
          onConfirm={() => onDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <a key="deletable">删除</a>
        </Popconfirm>,
      ],
    },
  ];
  const uploadProps: UploadProps = {
    withCredentials: true,
    name: 'file',
    data: {
      currentUserId: initialState?.currentUser?.id,
    },
    action: errorConfig.baseURL + '/monthly-planning/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        if (info.file.response.code === 0 && info.file.response.data) {
          props.rightActionRef.current?.reload();
          props.leftActionRef.current?.reload();
          openNotification('success',info.file.response.data);
        } else {
          openNotification('warning',"提交数据无效，请检查上传文件！");
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };
  return (
    <>
      {contextHolder}
      <div style={{display: "flex", justifyContent: "space-between", margin: "10px 10px 0px 10px"}}>
        <Space>
          <Button
            type="primary"
            onClick={() => {
              if (props.clickMonthlyPlanningNumber?.productionLineCode === undefined) {
                message.warning("未选择产线")
                return;
              }
              setSelectValue('');
              props.rightActionRef.current?.addEditRecord?.({
                id: (Math.random() * 1000000).toFixed(0),
                type: 'addProductionLineKeyProcess',
              });
            }}
            icon={<PlusOutlined/>}
          >
            新增 关键工序
          </Button>
        </Space>
        <Space>
          <Button
            type="dashed"
            key="downloadMonthlyPlanning"
            icon={<DownloadOutlined/>}
            onClick={() => {
              const url = errorConfig.baseURL + '/monthly-planning/download?';
              let params = "commitUserId=" + initialState?.currentUser?.id + "&";
              window.location.href = url + params;
            }}
          >
            导出数据
          </Button>
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined/>}>上传数据</Button>
          </Upload>
        </Space>
      </div>
      <EditableProTable<API.MonthlyPlanningKeyProcessDTO>
        scroll={{y: 'calc(100vh - 205px)'}}
        rowKey="id"
        actionRef={props.rightActionRef}
        headerTitle={props.clickMonthlyPlanningNumber?.productionLineName || '未选中产线'}
        // maxLength={5}
        // 关闭默认的新建按钮
        recordCreatorProps={false}
        columns={columns}
        request={() => initKeyProcessList()}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          form,
          editableKeys,
          onSave: async (key, row: any) => {
            if (row.type === 'addProductionLineKeyProcess') {
              await onSave(row);
            } else {
              await onEdit(row);
            }
            // 如果是原始数据没有username等属性值，则修改
          },
          onChange: setEditableRowKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
        }}
      />
    </>
  );
};

export default RightTable;
